package cc.wfu.type.service;

import cc.wfu.type.common.Constants;
import cc.wfu.type.common.SecurityConstant;
import cc.wfu.type.util.JwtUtil;
import cc.wfu.type.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc:
 * @Date: 2024-05-21-23:51
 */
@Slf4j
public class JwtAuthServiceSupport {

    @Resource
    protected JwtUtil jwtUtil;
    @Resource
    protected RedisUtil redisUtil;
    @Resource
    protected AuthenticationManager authenticationManagerBean;

    public void authenticate(String username, String textPassword) {
        // 1.获取 AuthenticationManager 的 authenticate 方法进行认证
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(username, textPassword);
        Authentication authentication = authenticationManagerBean.authenticate(authenticationToken);
        if (Objects.isNull(authentication)) {
            // 认证不通过
            throw new RuntimeException(Constants.ResponseErrorSimple.LOGIN_AUTHENTICATE_ERROR.getInfo());
        }
        // 2. 将认证信息存储到redis中
        String item = Constants.PREFIX + Constants.UNDER_LINE + username;
        User user = (User) authentication.getPrincipal();
        redisUtil.hashSet(SecurityConstant.TOKEN_KEY, item, user, SecurityConstant.TOKEN_EXPIRE);
    }
}
